/*
 * @Author: Lin Hongwei
 * @Date: 2022-10-30 21:43:17
 * @LastEditTime: 2022-11-03 22:05:56
 * @LastEditors: Lin Hongwei
 * @email: 1365755396@qq.com
 * @CSDN: https://blog.csdn.net/weixin_45429409
 * @Description: service封装公用父类
 * - 这里使用箭头箭头函数避免this指针问题
 */
const { query } = require("../utils/db");

class CRUDService {
  //表名
  tableName = ''
  constructor(tableName) {
    this.tableName = tableName
  }
  /**
   * @description: 
   * @param {*} sortColumn 需要排序的字段名
   */
  query = async (params, sortColumn) => {
    let sql = `select * from ${this.tableName} `;
    let values = params;
    if (params) {
      const keys = Object.keys(params);
      values = Object.values(params);
      let str = keys.join(' = ? and ');
      str.length && (sql = `${sql} where ${str} = ? `);
    }
    if (sortColumn) sql += ` order by ${sortColumn} `;
    return query(sql, values || {});
  }
  create = async (params) => {
    let sql = `insert into ${this.tableName} set ?`;
    return query(sql, params);
  }
  update = async (params) => {
    let sql = `update ${this.tableName} set ? where  ?`;
    return query(sql, params);
  }
  delete = async (params) => {
    let sql = `delete from ${this.tableName} where ?`;
    return query(sql, params)
  }
  /**
   * @description: 
   * @param {*} params {fromId:移动的id,toId:要移动到的位置}
   * @param {*} type 1:在更新的时候需要更新看板id
   * @return {*}
   */
  sort = async (params, type = 0) => {
    let sql = `call table_sort_procedure('${this.tableName}',?,?,${type})`;
    return query(sql, params);
  }
}

module.exports = CRUDService